#!/bin/bash

# 启动脚本
# 用于快速启动应用并进行测试

# 颜色定义
GREEN="\033[0;32m"
YELLOW="\033[1;33m"
BLUE="\033[0;34m"
RED="\033[0;31m"
NC="\033[0m" # No Color

# 打印带颜色的消息
echo_color() {
    echo -e "${1}${2}${NC}"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        echo_color "$RED" "错误: 命令 '$1' 未找到，请先安装。"
        exit 1
    fi
}

# 检查必要的命令
check_command python3
check_command uv

# 创建虚拟环境并安装依赖
setup_env() {
    echo_color "$BLUE" "=== 创建虚拟环境并安装依赖 ==="
    
    # 检查虚拟环境是否已存在
    if [ ! -d ".venv" ]; then
        echo_color "$YELLOW" "创建虚拟环境..."
        uv venv
    else
        echo_color "$YELLOW" "虚拟环境已存在，跳过创建"
    fi
    
    # 激活虚拟环境
    echo_color "$YELLOW" "激活虚拟环境..."
    source .venv/bin/activate
    
    # 安装依赖
    echo_color "$YELLOW" "安装依赖..."
    uv pip install -r requirements.txt
    
    # 创建环境变量文件
    if [ ! -f ".env" ]; then
        echo_color "$YELLOW" "创建环境变量文件..."
        cp .env.example .env
        echo_color "$GREEN" "已创建 .env 文件，请根据需要修改配置"
    else
        echo_color "$YELLOW" ".env 文件已存在，跳过创建"
    fi
}

# 初始化数据库
init_database() {
    echo_color "$BLUE" "=== 初始化数据库 ==="
    python3 init_db.py
}

# 运行测试
run_tests() {
    echo_color "$BLUE" "=== 运行测试 ==="
    python3 -m unittest tests.py
}

# 启动应用
start_app() {
    echo_color "$BLUE" "=== 启动应用 ==="
    echo_color "$GREEN" "应用将在 http://localhost:5000 上运行"
    echo_color "$YELLOW" "按 Ctrl+C 停止应用"
    python3 app.py
}

# 主函数
main() {
    echo_color "$BLUE" "===== Flask RBAC API 启动脚本 ====="
    
    # 参数处理
    case "$1" in
        setup)
            setup_env
            ;;
        init)
            init_database
            ;;
        test)
            run_tests
            ;;
        start)
            start_app
            ;;
        all)
            setup_env
            init_database
            run_tests
            start_app
            ;;
        *)
            echo_color "$YELLOW" "用法: $0 {setup|init|test|start|all}"
            echo_color "$YELLOW" "  setup - 创建虚拟环境并安装依赖"
            echo_color "$YELLOW" "  init  - 初始化数据库"
            echo_color "$YELLOW" "  test  - 运行测试"
            echo_color "$YELLOW" "  start - 启动应用"
            echo_color "$YELLOW" "  all   - 执行所有上述步骤"
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"